package 模拟;

import java.util.HashMap;
import java.util.Map;

public class 数青蛙5 {
    //https://leetcode.cn/problems/minimum-number-of-frogs-croaking/description/
    public int minNumberOfFrogs1(String croakOfFrogs) {
        // 字符 -> <— 角标 -> 次数
        Map<Character,Integer> map1 = new HashMap<>();
        map1.put('c',0);
        map1.put('r',0);
        map1.put('o',0);
        map1.put('a',0);
        map1.put('k',0);
        Map<Character,Integer> map2 = new HashMap<>();
        map2.put('c',0);
        map2.put('r',1);
        map2.put('o',2);
        map2.put('a',3);
        map2.put('k',4);
        Map<Integer,Character> map3 = new HashMap<>();
        map3.put(0,'c');
        map3.put(1,'r');
        map3.put(2,'o');
        map3.put(3,'a');
        map3.put(4,'k');
        int cur = 0, len = croakOfFrogs.length();
        while (cur < len) {
            if(croakOfFrogs.charAt(cur) == 'c') {
                if(map1.get('k') != 0) {
                    map1.put('k',map1.get('k') - 1);
                    map1.put('c',map1.get('c') + 1);
                }else {
                    map1.put('c',map1.get('c') + 1);
                }
            }
            else {
                char ch = croakOfFrogs.charAt(cur);
                if(map1.get(map3.get(map2.get(ch) - 1)) > 0) {
                    map1.put(map3.get(map2.get(ch) - 1),map1.get(map3.get(map2.get(ch) - 1)) - 1);
                    map1.put(ch,map1.get(ch) + 1);
                }else {
                    return -1;
                }
            }
            cur++;
        }
        for (int i = 0; i < 4; i++) {
            if(map1.get(map3.get(i)) != 0) return -1;
        }
        return map1.get('k');
    }
    public int minNumberOfFrogs(String c) {
        // 字符 -> 角标 -> 次数
        char[] croakOfFrogs = c.toCharArray();
        String t = "croak";
        int n = t.length();
        int[] hash = new int[n]; // 角标 -> 次数
        Map<Character,Integer> index = new HashMap<>(); // 字符 -> 角标
        for (int i = 0; i < n; i++)
            index.put(t.charAt(i),i);
        for (char ch : croakOfFrogs) {
            if(ch == t.charAt(0)) {
                if(hash[n - 1] != 0) hash[n - 1]--;
                hash[0]++;
            }else {
                int i = index.get(ch);
                if(hash[i - 1] == 0) return -1;
                hash[i - 1]--;
                hash[i]++;
            }
        }
        for (int i = 0; i < n - 1; i++)
            if(hash[i] != 0) return -1;
        return hash[n - 1];
    }
}
